import sys
import os

# 添加Odoo路径
sys.path.append('f:\\odoo')
os.environ['PYTHONPATH'] = 'f:\\odoo'

# 导入Odoo核心模块
import odoo
from odoo import api, models, registry, SUPERUSER_ID
from odoo.modules.registry import Registry

# 初始化Odoo环境
odoo.tools.config.parse_config(['--addons-path=f:\\odoo\\addons'])

dbname = 'ncs'  # 替换为你的数据库名称

# 连接数据库
with registry(dbname).cursor() as cr:
    env = api.Environment(cr, SUPERUSER_ID, {})

    # 先检查模块状态
    module = env['ir.module.module'].search([('name', '=', 'estate')])
    if not module:
        print("模块未找到，请确保模块在addons目录中")
        sys.exit(1)
    
    print(f"模块状态: {module.state}")
    if module.state != 'installed':
        print("尝试安装模块...")
        try:
            module.button_install()
            cr.commit()
            print("模块安装成功")
            # 强制刷新注册表
            print("刷新模型注册表...")
            # After module installation
            Registry.new(dbname)
            env = Environment(cr, SUPERUSER_ID, {})
            
            # More detailed model check
            try:
                model = env['ir.model'].search([('model', '=', 'estate.property')])
                if not model:
                    print("Model not found in ir_model table")
                    sys.exit(1)
                    
                # Verify model is actually loadable
                test_model = env['estate.property']
                print("Model successfully loaded")
            except Exception as e:
                print(f"Error loading model: {str(e)}")
                sys.exit(1)
        except Exception as e:
            print(f"模块安装失败: {e}")
            sys.exit(1)

    # 安装并刷新后，重新获取环境
    cr = registry(dbname).cursor()
    env = api.Environment(cr, SUPERUSER_ID, {})

    # 检查estate模型是否存在
    try:
        env['estate.property']
    except KeyError:
        print(f"模型 'estate.property' 不存在")
        sys.exit(1)
    # Get the model record first
    model = env['ir.model'].search([('model', '=', 'estate.property')])
    if not model:
        print("Model record not found in ir_model")
        sys.exit(1)
    try:
        new_property = env['estate.property'].create({
            'name': 'Beautiful House',
            'expected_price': 500000,
            'postcode': '10001',
            'date_availability': '2023-12-01',
            'description': 'Luxury villa with ocean view'
        })
        print(f"Created property with ID: {new_property.id}")
        env.cr.commit()
    except Exception as e:
        print(f"Error creating property: {e}")
        raise
    # Create external ID linked to this model
    # if not env['ir.model.data'].search([('name', '=', 'model_estate')]):
    #     env['ir.model.data'].create({
    #         'name': 'model_estate',
    #         'model': 'ir.model',
    #         'module': 'estate',
    #         'res_id': model.id  # Use the actual model record ID
    #     })
    #     print(f"Created external ID 'model_estate' for model ID {model.id}")
    # 创建model_estate外部ID
    # if not env['ir.model.data'].search([('name', '=', 'model_estate'), ('model', '=', 'ir.model')]):
    #     env['ir.model.data'].create({
    #         'name': 'model_estate',
    #         'model': 'ir.model',
    #         'module': 'estate',
    #         'res_id': env['ir.model'].search([('model', '=', 'estate')]).id
    #     })
    #     print("已创建'model_estate'外部ID")
    # try:
    #     model = env['estate.property']
    #     print(f"模型 'estate.property' 存在")
    # except KeyError:
    #     print("模型 'estate.property' 不存在，可能是模型定义有问题")
    #     # 检查ir.model表中是否有该模型
    #     model_record = env['ir.model'].search([('model', '=', 'estate.property')])
    #     if model_record:
    #         print(f"模型在数据库中存在，ID: {model_record.id}")
    #     else:
    #         print("模型在数据库中不存在，请检查模型定义")
    #     sys.exit(1)

    # # 检查外部ID是否存在
    # xmlid = 'model_estate'  # 修改为与模型一致的名称
    # try:
    #     # 尝试查找外部ID
    #     res_id = env['ir.model.data']._xmlid_to_res_id(xmlid)
    #     print(f"外部ID '{xmlid}' 已存在，对应ID: {res_id}")
    # except ValueError:
    #     print(f"外部ID '{xmlid}' 不存在，正在创建...")
    #     # 获取模型的ID
    #     model_id = env['ir.model']._get('estate.property').id  # 修改为'estate'
    #     # 创建ir.model.data记录
    #     env['ir.model.data'].create({
    #         'name': 'estate',
    #         'module': 'estate',
    #         'model': 'ir.model',
    #         'res_id': model_id
    #     })
    #     print(f"外部ID '{xmlid}' 创建成功")
    #     cr.commit()